<template>
  <a-card :bordered="false">
    <div class="table-page-search-wrapper">
      <a-form layout="inline">
        <a-row :gutter="48">
          <a-col :md="8" :sm="24">
            <a-form-item label="商户订单号">
              <a-input v-model="queryParam.outTradeNo" placeholder="请输入"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item label="上级机构">
              <a-tree-select
                :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                placeholder='请选择商户'
                allowClear
                treeDefaultExpandAll
                :treeData="treeData"
                v-model="queryParam.code"
                @change="storeChange"
              >
              <span style="color:#08c" slot="title" slot-scope="{key}"
                    v-decorator="['key',{rules: [{ required: true, message: '请选择商户' }]}]">
                {{value}}
              </span>
              </a-tree-select>
            </a-form-item>
          </a-col>
          <template v-if="advanced">
            <a-col :md="8" :sm="24">
              <a-form-item label="店员">
                <a-select v-model="queryParam.storeUserId"
                          allowClear
                >
                  <a-select-option v-for="item in storeList" :key="item.id">{{item.username}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="订单状态">
                <a-select v-model="queryParam.orderStatus"
                          allowClear
                >
                  <a-select-option v-for="item in OrderStatus" :key="item.id">{{item.name}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="支付方式">
                <a-select :defaultValue="defauleTypeValue" allowClear @change="handleProvinceChange">
                  <a-select-option v-for="province in provinceData" :key="province">{{province}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :md="8" :sm="24">
              <a-form-item label="交易类型">
                <a-select v-model="secondCity" allowClear @change="handleProvinceChangeTo">
                  <a-select-option v-for="city in cities" :key="city">{{city}}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="起始时间">
                <a-date-picker
                  format="YYYY-MM-DD"
                  v-model="queryParam.startTime"
                  placeholder="开始"
                />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="起始时间">
                <a-date-picker
                  format="YYYY-MM-DD"
                  placeholder="结束"
                  v-model="queryParam.enTime"
                />
              </a-form-item>
            </a-col>
          </template>

          <a-col :md="8" :sm="24">
            <span class="table-page-search-submitButtons">
              <a-button v-action:query type="primary" @click="$refs.table.refresh(true)">查询</a-button>
              <a-button v-action:query style="margin-left: 8px" @click="resetParams()">重置</a-button>
               <a @click="toggleAdvanced" style="margin-left: 8px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="table-operator">
      <a-button type="primary" @click="exportExcell()">导出EXCEL</a-button>
    </div>

    <div class="table-operator">
      <span title="包含支付成功/退款/押金的所有单数">交易单数：<a-tag color="purple">{{statistics.sumCount?statistics.sumCount:0}} 单</a-tag></span>
      <span title="包含支付成功/退款/押金的所有金额">交易金额：<a-tag color="purple">{{statistics.sumFee?statistics.sumFee:0.00}} 元</a-tag></span>
      <span title="商户实际到账金额">实收金额：<a-tag
        color="purple">{{statistics.settlementFee?statistics.settlementFee:0.00}} 元</a-tag></span>
      <span title="已经成功退款的单数">退款单数：<a-tag
        color="red">{{statistics.refundCount?statistics.refundCount:0}} 单</a-tag></span>
      <span title="已经成功退款的金额">退款金额：<a-tag
        color="red">{{statistics.refundFee?statistics.refundFee:0.00}} 元</a-tag></span>
      <span title="包含免充值券/代金券/随机立减等优惠的金额">优惠金额：<a-tag color="red">{{statistics.couponTotalFee?statistics.couponTotalFee:0.00}} 元</a-tag></span>
      <span title="冻结中尚未消费的单数">押金单数：<a-tag color="green">{{statistics.depositCount?statistics.depositCount:0}} 单</a-tag></span>
      <span title="冻结中尚未消费的金额">押金金额：<a-tag color="green">{{statistics.depositTotalFee?statistics.depositTotalFee:0.00}} 元</a-tag></span>
    </div>
    <div class="table-operator">
      <span title="微信支付成功/押金已消费的单数，不包含退款">微信单数：<a-tag
        color="green">{{statistics.wxCount?statistics.wxCount:0}} 单</a-tag></span>
      <span title="微信支付成功/押金已消费的单数，不包含退款">微信金额：<a-tag color="green">{{statistics.wxFee?statistics.wxFee:0.00}} 元</a-tag></span>
      <span title="支付报支付成功的单数，不包含退款">支付宝单数：<a-tag
        color="blue">{{statistics.aliCount?statistics.aliCount:0}} 单</a-tag></span>
      <span title="支付报支付成功的金额，不包含退款">支付宝金额：<a-tag
        color="blue">{{statistics.aliFee?statistics.aliFee:0.00}} 元</a-tag></span>
      <span title="商户会员余额支付的单数，无现金交易">会员单数：<a-tag
        color="#6F00D2">{{statistics.memberCount?statistics.memberCount:0}} 单</a-tag></span>
      <span title="商户会员余额支付的金额，无现金交易">会员金额：<a-tag
        color="#6F00D2">{{statistics.memberFee?statistics.memberFee:0.00}} 元</a-tag></span>
      <span title="第三方通道指定收款的单数">通用通单数：<a-tag
        color="#00AEAE">{{statistics.tytCount?statistics.tytCount:0}} 单</a-tag></span>
      <span title="第三方通道指定收款的金额">通用通金额：<a-tag
        color="#00AEAE">{{statistics.tytFee?statistics.tytFee:0.00}} 元</a-tag></span>
    </div>
    <s-table
      ref="table"
      size="default"
      :columns="columns"
      :data="loadData"
      :scroll="{x:1200}"
    >
      <template slot-scope="text" slot="orderStatus">
        <a-tag v-if="text==0" color="red">
          {{ text | statusFilter }}
        </a-tag>
        <a-tag v-if="text==1" color="blue">
          {{ text | statusFilter }}
        </a-tag>
        <a-tag v-if="text==5" color="#EEC900">
          {{ text | statusFilter }}
        </a-tag>
        <a-tag v-if="text==2 || text== 3 || text == 4" color="red">
          {{ text | statusFilter }}
        </a-tag>
      </template>

      <span slot="settlementTotalFee" slot-scope="text">
        {{ text?text/ 100 :0.00}}元
      </span>
      <span slot="memberTotalFee" slot-scope="text">
        {{ text?text / 100:0.00 }}元
      </span>

      <template slot-scope="text" slot="payType">
        <a-tag v-if="text==1" color="green">
          {{ text | payTypeFilter }}
        </a-tag>
        <a-tag v-if="text==2" color="blue">
          {{ text | payTypeFilter }}
        </a-tag>
        <a-tag v-if="text==3" color="#6F00D2">
          {{ text | payTypeFilter }}
        </a-tag>
        <a-tag v-if="text==4" color="#00AEAE">
          {{ text | payTypeFilter }}
        </a-tag>
      </template>
      <template slot-scope="text" slot="profitSharing">
        <a-tag v-if="text=='Y'" color="#2db7f5">
          {{ text | profitSharingFilter }}
        </a-tag>
        <a-tag v-else color="#F50">
          {{ text | profitSharingFilter }}
        </a-tag>
      </template>
      <template slot-scope="text" slot="profitSharingStatus">
        <a-tag v-if="text==1" color="cyan">
          {{ text | profitSharingStatusFilter }}
        </a-tag>
        <a-tag v-if="text==2" color="blue">
          {{ text | profitSharingStatusFilter }}
        </a-tag>
        <a-tag v-if="text==3" color="red">
          {{ text | profitSharingStatusFilter }}
        </a-tag>
        <a-tag v-if="text==0" color="red">
          {{ text | profitSharingStatusFilter }}
        </a-tag>
      </template>
      <span slot="action" slot-scope="text,record">
        <template>
          <a v-action:other @click="EditTap(record)">查看详情</a>
        </template>
      </span>
    </s-table>


  </a-card>
</template>

<script>
  import STable from '@/components/table/'
  import Edit from './Edit'
  import {selectList, del, selectByCode,exportExcel} from '@/api/transactionService/order'
  import {selectTree} from '@/api/storeService/store'
  import moment from 'moment'
  import {formatDate} from '@/api/common/DateFmt'

  const provinceData = ['全部', '微信', '支付宝', '会员支付', '通用通'];
  let cityData = {
    '全部': ['全部'],
    '微信': ['全部', '人脸', '主扫', '被扫', '押金'],
    '支付宝': ['全部', '人脸', '主扫', '被扫'],
    '会员支付': ['全部', '默认类型'],
    '通用通': ['全部', '人脸', '主扫', '被扫']
  }

  export default {
    components: {
      STable,
      Edit
    },
    //--############  data() ###############-->
    data() {
      return {
        provinceData,
        cityData,
        cities: [],
        secondCity: [],
        defauleTypeValue: provinceData[0],
        description: '',
        // 高级搜索 展开/关闭
        advanced: false,
        setKey: '',

        // 查询参数
        queryParam: {},
        storeList: [],
        OrderStatus: [{id: 1, name: '已支付'}, {id: 3, name: '已退款'}, {id: 5, name: '押金支付'}], //订单状态
        statistics: {
          sumCount: 0,
          sumFee: 0,
          settlementFee: 0,
          couponTotalFee: 0,
          refundCount: 0,
          refundFee: 0,
          aliCount: 0,
          aliFee: 0,
          memberCount: 0,
          memberFee: 0,
          tytCount: 0,
          tytFee: 0,
          wxCount: 0,
          wxFee: 0,
          depositCount: 0,
          depositTotalFee: 0
        },
        // 表头
        columns: [
          {
            title: '商户订单号',
            dataIndex: 'outTradeNo'
          },
          {
            title: '商户名称',
            dataIndex: 'merchantName'
          },
          {
            title: '门店名称',
            dataIndex: 'storeName'
          },


          {
            title: '订单金额',
            dataIndex: 'memberTotalFee',
            scopedSlots: {customRender: 'memberTotalFee'}
          },
          {
            title: '实收金额',
            dataIndex: 'settlementTotalFee',
            scopedSlots: {customRender: 'settlementTotalFee'}
          },
          // {
          //   title: '实付金额',
          //   dataIndex: 'realPayFee',
          //   scopedSlots: {customRender: 'realPayFee'}
          // },
          // {
          //   title: '优惠金额',
          //   dataIndex: 'couponFee',
          //   scopedSlots: {customRender: 'couponFee'}
          // },
          {
            title: '支付方式',
            dataIndex: 'payType',
            scopedSlots: {customRender: 'payType'}
          },
          {
            title: '支付状态',
            dataIndex: 'orderStatus',
            scopedSlots: {customRender: 'orderStatus'}
          },
          {
            title: '创建时间',
            dataIndex: 'createdTime'
          },
          /* {
             title: '是否分账',
             dataIndex: 'profitSharing',
             scopedSlots: {customRender: 'profitSharing'}
           },
           {
             title: '分账状态',
             dataIndex: 'profitSharingStatus',
             scopedSlots: {customRender: 'profitSharingStatus'}
           },*/

          {
            title: '操作',
            // fixed: 'right',
            width: 90,
            scopedSlots: {customRender: 'action'}
          }
        ],
        // 加载数据方法 必须为 Promise 对象
        loadData: parameter => {
          const beginTimeQuery = this.queryParam.startTime //undefined
          const endTimeQuery = this.queryParam.enTime //undefined
          if (beginTimeQuery != undefined) {//点击查询

            this.queryParam.beginTime = moment(beginTimeQuery).format('YYYY-MM-DD') + ' 00:00:00'
          }
          if (beginTimeQuery != undefined) {
            this.queryParam.endTime = moment(endTimeQuery).format('YYYY-MM-DD') + ' 23:59:59'
          }
          return selectList(Object.assign(parameter, this.queryParam))
            .then(res => {
              console.log(res)
              this.statistics = res.result.statistics
              return res.result.pageInfo
            })
        },
        treeData: [],
        selectedRowKeys: [],
        selectedRows: [],
      }
    },

    created() {
      const _this = this
      const params = {'ctrlType': '1,2', 'displayType': '1,2,3,4'}
      /*ctrlType:控制层级结构不能操作，1，服务商，2，代理商，3商户，4，门店
      * displayType:控制层级显示，必须是连续，1，服务商，2，代理商，3商户，4，门店
      * */
      selectTree(params).then(res => {
        if (res.code === 200) {
          if (res.result == null) {
            return
          }
          _this.treeData = res.result
        } else {
          this.$notification.error({
            message: '错误',
            description: res.message,
            duration: 4
          })
        }
      })
    },
    methods: {
      //查看详情
      EditTap(record) {
        this.$emit('onEdit', record)
      },
      resetParams() {
        this.queryParam = {}
        this.defauleTypeValue = provinceData[0]
      },
      //支付类型
      handleProvinceChange(value) {
        if (value == null || value == '全部') {
          this.queryParam.payType = null
          this.queryParam.tradeType = null
          this.cities = null
          this.secondCity = null
          return
        }

        if (value == '微信') {
          this.queryParam.payType = 1
        } else if (value == '支付宝') {
          this.queryParam.payType = 2
        } else if (value == '会员支付') {
          this.queryParam.payType = 3
        } else if (value == '通用通') {
          this.queryParam.payType = 4
        }
        this.cities = cityData[value];
        this.secondCity = cityData[value][0];
      },
      handleProvinceChangeTo(e) {
        if (e == '全部') {
          this.queryParam.tradeType = null
        } else if (e == '人脸') {
          this.queryParam.tradeType = 'FACEPAY'
        } else if (e == '主扫') {
          this.queryParam.tradeType = 'SCAN'
        }
        else if (e == '被扫') {
          this.queryParam.tradeType = 'SWEPT'
        }
        else if (e == '押金') {
          this.queryParam.tradeType = 'DEPOSIT'
        }

      },

      storeChange(e) {
        selectByCode(e).then(res => {
          this.storeList = res.result
        })
      },
      handleDel(row) {
        const _this = this
        this.$confirm({
          title: '警告',
          content: `真的要删除 ${row.name} 吗?`,
          okText: '删除',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            // 在这里调用删除接口
            del(row.id).then(res => {
              _this.$message.info(res.message)
              _this.$refs.table.refresh()
            })
          },
          onCancel() {
            console.log('Cancel')
          }
        })
      },
      toggleAdvanced() {
        this.advanced = !this.advanced
      },
      handleOk() {
        // 新增/修改 成功时，重载列表
        this.$refs.table.refresh(false)
      },
      onSelectChange(selectedRowKeys, selectedRows) {
        this.selectedRowKeys = selectedRowKeys
        this.selectedRows = selectedRows
      },
      exportExcell() {
        const _this = this
        this.$confirm({
          title: '警告',
          content: `确认导出当前查询条件下的所有交易记录？`,
          okText: '确认',
          okType: 'danger',
          cancelText: '取消',
          onOk() {
            exportExcel(_this.queryParam).then(res => {
              const link = document.createElement('a')
              let blob = new Blob([res], {type: 'application/vnd.ms-excel'});
              link.style.display = 'none'
              link.href = URL.createObjectURL(blob);
              let num = ''
              for (let i = 0; i < 10; i++) {
                num += Math.ceil(Math.random() * 10)
              }
              link.setAttribute('download', '交易记录('+ formatDate(new Date(), "yyyy-MM-dd")+'导出).xlsx')
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link)
            })
          },
          onCancel() {
            console.log('Cancel')
          }
        })
      },
    },
    //--############  methods() ###############-->
    //--############  filters() ###############-->
    filters: {
      statusFilter(state) {
        const statusMap = {
          0: '未支付',
          1: '已支付',
          2: '支付失败',
          3: '已退款',
          4: '已撤销',
          5: '押金支付'
        }
        return statusMap[state]
      },
      payTypeFilter(type) {
        const statusMap = {
          1: '微信',
          2: '支付宝',
          3: '会员支付',
          4: '通用通'
        }
        return statusMap[type]
      },
      profitSharingStatusFilter(type) {
        const statusMap = {
          0: '未分账',
          1: '分账中',
          2: '分账成功',
          3: '分账失败'
        }
        return statusMap[type]
      },
      profitSharingFilter(type) {
        const statusMap = {
          'Y': '是',
          'N': '否'
        }
        return statusMap[type]
      }
    }
    //--############  filters() ###############-->
  }
</script>
